/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package contest.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
 *
 * @author Admin
 */
public class SqlBundle {

    static SqlBundle queryBundle;
    Map<String, ResourceBundle> resources;
    Boolean isBuilt;

    private SqlBundle() {
        this.resources = new HashMap<String, ResourceBundle>();
        this.isBuilt = false;
    }

    public void buildPath(String locationPath) throws MalformedURLException {

        if (!this.isBuilt && !locationPath.equals("")) {
            File file = new File(locationPath);
            int size = 0;
            File[] fileList = null;
            if (file != null) {
                fileList = file.listFiles();
                size = file.listFiles().length;
            }
            int i = 0;
            for (i = 0; fileList != null && i < size; i++) {
                String propertyName = fileList[i].getName().replace(".properties", "");
                String extension = FileUtil.getExtension(fileList[i].getAbsolutePath());
                if (propertyName != null && extension.equals("properties")) {
                    URL[] urls = {file.toURI().toURL()};
                    ClassLoader loader = new URLClassLoader(urls);
                    this.resources.put(propertyName, ResourceBundle.getBundle(propertyName, Locale.getDefault(), loader));
                }
            }
            if (i > 0) {
                this.isBuilt = true;
            }
        }

    }

    public static SqlBundle getInstance() {
        if (SqlBundle.queryBundle == null) {
            SqlBundle.queryBundle = new SqlBundle();
        }
        return SqlBundle.queryBundle;
    }

    public Boolean isBuilt() {
        return this.isBuilt;
    }

    public ResourceBundle getResoureBundle(String name) {
        return this.resources.get(name);
    }

    public void resetBuild(String locationPath) throws Exception {
        this.isBuilt = false;
        this.buildPath(locationPath);
    }
}
